<template>
  <a-checkbox-group
    v-model:value="checkValue"
    :name="name"
    :options="options1"
    :disabled="disabled"
    :min="min"
    :max="max"
  >
    <slot />
    <!-- eslint-disable-next-line vue/no-template-shadow -->
    <template v-if="$slots.label" #label="{ value }">
      <slot name="label" :value="value" />
    </template>
  </a-checkbox-group>
</template>
<script>
import { defineComponent, computed } from 'vue'
import { CheckboxGroup } from 'ant-design-vue'
export default defineComponent({
  name: 'ZCheckboxGroup',
  components: {
    ACheckboxGroup: CheckboxGroup
  },
  props: {
    min: {
      type: [String, Number],
      default: undefined
    },
    max: {
      type: [String, Number],
      default: undefined
    },
    value: {
      type: [String, Array, Number],
      default: undefined
    },

    disabled: Boolean,
    name: {
      type: String,
      default: undefined
    },
    options: {
      type: Array,
      default: undefined
    }
  },
  setup(props, _ref) {
    const checkValue = computed({
      get() {
        return props.value
      },
      set(val) {
        if (props.max || props.min) {
          updateVal(val)
        }
        _ref.emit('update:value', val)
      }
    })

    const options1 = computed(() =>
      props.options ? JSON.parse(JSON.stringify(props.options)) : undefined
    )

    const updateVal = (val) => {
      if (val && val.length && options1?.value?.forEach) {
        if (props.max || props.min) {
          options1.value.forEach(i => {
            if (props.min && !props.max) {
              if (val.length <= props.min && val.indexOf(i.value) > -1) {
                i.disabled = true
              } else {
                i.disabled = props.options.find(a => a.value === i.value).disabled
              }
            }
            if (props.max && !props.min) {
              if (val.length >= props.max && val.indexOf(i.value) === -1) {
                i.disabled = true
              } else {
                i.disabled = props.options.find(a => a.value === i.value).disabled
              }
            }
            if (props.max && props.min) {
              if (val.length <= props.min && val.indexOf(i.value) > -1) {
                i.disabled = true
              } else if (val.length >= props.max && val.indexOf(i.value) === -1) {
                i.disabled = true
              } else {
                i.disabled = props.options.find(a => a.value === i.value).disabled
              }
            }
          })
        }
      }
    }

    updateVal(props.value)

    return {
      checkValue,
      options1
    }
  }
})
</script>
